package com.fand.manager.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fand.common.exception.BusinessException;
import com.fand.manager.entity.SysRole;
import com.fand.manager.entity.SysUserRole;
import com.fand.manager.mapper.SysRoleMapper;
import com.fand.manager.mapper.SysUserRoleMapper;
import com.fand.manager.model.userrole.SysUserRolePostDTO;
import com.fand.manager.model.userrole.SysUserRoleReturnDTO;
import com.fand.manager.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author javaboy
 * @since 2021-06-07
 */
@Service
@RefreshScope
public class SysUserRoleServiceImpl implements ISysUserRoleService {

    @Value("${system.root.usercode:admin}")
    private String rootUserCode;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysRoleMapper     sysRoleMapper;

    @Override
    public SysUserRoleReturnDTO getRoleAndNRole(Long id) {
        SysUserRoleReturnDTO sysUserRoleReturnDTO = SysUserRoleReturnDTO.builder().build();
        if (Objects.isNull(id)) {
            throw new BusinessException("参数id不能为空");
        }
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>().eq("user_id", id);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(sysUserRoles)) {
            List<Long> userRoles = sysUserRoles.parallelStream().map(sysUserRole -> sysUserRole.getRoleId()).collect(Collectors.toList());
            sysUserRoleReturnDTO.setUserRoles(userRoles);
        }

        List<SysRole> sysRoles = sysRoleMapper.selectList(new QueryWrapper<>());
        if (CollUtil.isNotEmpty(sysRoles)) {
            List<SysUserRoleReturnDTO.ReturnDTO> noRoleReturnDTOs = sysRoles.parallelStream().map(sysRole ->
                    {
                        SysUserRoleReturnDTO.ReturnDTO sysRoleReturnDTO = new SysUserRoleReturnDTO.ReturnDTO();
                        sysRoleReturnDTO.setTitle(sysRole.getName()).setValue(sysRole.getId());
                        return sysRoleReturnDTO;
                    }
            ).collect(Collectors.toList());
            sysUserRoleReturnDTO.setRoles(noRoleReturnDTOs);
        }
        return sysUserRoleReturnDTO;
    }

    @Transactional
    @Override
    public Boolean saveUserRole(SysUserRolePostDTO sysUserRolePostDTO) {
        if(Objects.isNull(sysUserRolePostDTO)){
            throw new BusinessException("参数为空");
        }
        Long userId = sysUserRolePostDTO.getUserId();
        int type = sysUserRolePostDTO.getType();
        List<SysUserRolePostDTO.PostDTO> userRoles = sysUserRolePostDTO.getUserRoles();
        switch (type){
            case 0:
                List<SysUserRole> sysUserRoles = userRoles.stream().map(postDTO ->
                    SysUserRole.builder().userId(userId).roleId(postDTO.getValue()).createdBy(0L).updatedBy(0L).build()
                ).collect(Collectors.toList());
                sysUserRoles.stream().forEach(sysUserRole -> sysUserRoleMapper.insert(sysUserRole));
                break;
            case 1:
                List<Long> roleIds = userRoles.stream().map(postDTO -> postDTO.getValue()).collect(Collectors.toList());
                sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().eq("user_id",userId).in("role_id",roleIds));
                break;
        }
        return Boolean.TRUE;
    }

    @Override
    public List<String> listResourcesByUserCode(String userCode){
        if(StrUtil.isEmpty(userCode)){
            throw new BusinessException("非法参数");
        }
        List<String> resources = null;
        if(rootUserCode.equals(userCode)){
            resources = sysUserRoleMapper.listSources();
        }else{
            resources = sysUserRoleMapper.listSourcesByUsreCode(userCode);
        }
        return resources;
    }
}
